﻿using AutoMapper;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Linq;
using Tools.Core.Dtos;
using Tools.Core.Entities;
using Tools.Services.Interfaces;

namespace Tools.Modules.Dialogs.ViewModels
{
    public class MailReceiverViewModel : BindableBase,IDialogAware
    {
        private readonly IMailReceiverService _mrs;
        private readonly IMapper _mapper;

        private MailReceiverDto _receiver=new MailReceiverDto();
        public MailReceiverDto Receiver
        {
            get => _receiver;
            set=>SetProperty(ref _receiver, value);
        }

        public DelegateCommand SubmitReceiverCommand { get; private set; }
        public MailReceiverViewModel(IMapper mapper,IMailReceiverService mrs)
        {
            _mrs = mrs;
            _mapper = mapper;
            SubmitReceiverCommand = new DelegateCommand(async() =>
            {
                var r = _mapper.Map<MailReceiver>(Receiver);
                await _mrs.UpdateReceiverAsync(r);
            });
        }

        public string Title => "邮件接收人";

        public event Action<IDialogResult> RequestClose;

        public bool CanCloseDialog()
        {
            return true;
        }

        public void OnDialogClosed()
        {
            RequestClose?.Invoke(null);
        }

        public void OnDialogOpened(IDialogParameters parameters)
        {
            var receiver = parameters.GetValue<MailReceiverDto>("receiver");
            if (receiver != null)
            {
                Receiver = receiver;
            }
        }
    }
}
